﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CSP.Common.Web;
using CSP.Bll;
using CSP.Bll.IObjectBlls;
using System.Collections.ObjectModel;
using CSP.Model.CSPEnum;
using CSP.Web.UserControls;
using CSP.Web.Master;
using CSP.Model.CSP;

namespace CSP.Web.MyHome.ServiceManage
{
    public partial class Detail : CSPMyHome
    {
        private List<int> _searchIds;
        private List<int> SearchIds
        {
            get
            {
                return ViewState[SEARCHIDSKEY] as List<int>;

            }
            set
            {
                ViewState[SEARCHIDSKEY] = _searchIds = value;
            }
        }

        private const string SEARCHIDSKEY = "searchids";

        protected void Page_Load(object sender, EventArgs e)
        {
            //指定被选中的导航
            ((HomeMaster)Master).SelectedNavigationLink = MyHomeLeftNavigationLink.ServiceInfo;

            if (!IsPostBack)
            {
                if (Request["deleteid"] != null)
                {

                    string result = RemoveServiceInfo(Convert.ToInt32(Request["deleteid"]));
                    Response.ClearContent();
                    Response.Write(result);
                    Response.End();
                }
                if (Request["updateid"] != null)
                {
                    string result = UpdateServiceStatus(Convert.ToInt32(Request["updateid"]), Convert.ToInt32(Request["status"]));
                    Response.ClearContent();
                    Response.Write(result);
                    Response.End();
                }
                else
                {
                    BindDefaultUIByUserName();
                }

            }
        }
        protected string GetPaymentByCode(string paymentCode)
        {
            ServiceAsset asset = GetAssetData(paymentCode);
            if (asset != null)
            {
                return asset.Name;
            }
            return paymentCode;
        }

        private ServiceAsset GetAssetData(string id)
        {
            //List<AgeGroup> result = new List<AgeGroup>();
            //return result;

            CSP.Model.CSP.ServiceAsset result;
            using (var serviceTypeBll = CSPBllFactory.GetInstance().GetServiceAssetBll())
            {
                result = serviceTypeBll.GetDataById(Int32.Parse(id));
            }
            return result;
        }

        /// <summary>
        /// 通过用户名绑定默认UI
        /// </summary>
        private void BindDefaultUIByUserName()
        {
            SearchIds = GetIdsByUser();

            InitParm();
            this.S_Status.SelectedIndex = 0;
            ICollection<CSP.Model.CSP.ServiceInfo> serviceInfoes = FindByIds(SearchIds, U_ServicePager.PageIndex, U_ServicePager.PageSize);
            BindServiceInfoListUI(serviceInfoes);
        }

        /// <summary>
        /// 绑定ServiceInfo到List上
        /// </summary>
        private void BindServiceInfoListUI(ICollection<CSP.Model.CSP.ServiceInfo> serviceInfoes)
        {
            this.R_ServiceInfo.DataSource = serviceInfoes;
            this.R_ServiceInfo.DataBind();
        }

        /// <summary>
        /// 初始化参数
        /// </summary>
        private void InitParm()
        {
            SetPagerParm(0, 15, SearchIds.Count);
        }

        /// <summary>
        /// 设置分页参数
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        private void SetPagerParm(int pageIndex, int pageSize, int pageCount)
        {
            this.U_ServicePager.PageSize = pageSize;
            this.U_ServicePager.PageIndex = pageIndex;
            this.U_ServicePager.ItemCount = pageCount;
        }

        /// <summary>
        /// 根据用户信息获取Ids
        /// </summary>
        private List<int> GetIdsByUser()
        {
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();

            List<int> ids = new List<int>();
            using (IServiceInfoBll serviceInfoBll = bllFactory.GetServiceInfoBll())
            {
                ids = serviceInfoBll.FindIdsByUser(UserProvider.UserName);
            }
            return ids;
        }

        /// <summary>
        /// 根据用户信息获取Ids
        /// </summary>
        /// <returns></returns>
        private List<int> FindIdsByUser()
        {
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();

            List<int> ids = new List<int>();
            using (IServiceInfoBll serviceInfoBll = bllFactory.GetServiceInfoBll())
            {
                ids = serviceInfoBll.FindIdsByUser(UserProvider.UserName);
            }
            return ids;
        }

        /// <summary>
        /// 根据Title获取结果ID
        /// </summary>
        /// <returns></returns>
        private List<int> FindIdsByTitle()
        {
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();

            List<int> ids = new List<int>();
            using (IServiceInfoBll serviceInfoBll = bllFactory.GetServiceInfoBll())
            {
                ids = serviceInfoBll.FindByUserNameAndTitle(UserProvider.UserName, Txt_Title.Value.Trim());
            }
            return ids;
        }

        /// <summary>
        /// 根据Ids和status 获取结果Id
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        private List<int> FindIdsByIdsAndStatus(List<int> ids, ServiceInfoStatus status)
        {
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();

            List<int> serviceIds = new List<int>();
            using (IServiceInfoBll serviceInfoBll = bllFactory.GetServiceInfoBll())
            {
                serviceIds = serviceInfoBll.FindIdsByIdsAndStatus(ids, status);
            }
            return serviceIds;
        }

        /// <summary>
        /// 根据Ids 获取数据
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        private ICollection<CSP.Model.CSP.ServiceInfo> FindByIds(List<int> ids, int pageIndex, int pageSize)
        {
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();

            ICollection<CSP.Model.CSP.ServiceInfo> serviceInfoes = new Collection<CSP.Model.CSP.ServiceInfo>();
            using (IServiceInfoBll serviceInfoBll = bllFactory.GetServiceInfoBll())
            {
                serviceInfoes = serviceInfoBll.FindByIds(ids, pageIndex, pageSize);
            }
            return serviceInfoes;
        }

        protected void U_ServicePager_IndexChange(object sender, EventArgs e)
        {
            ICollection<CSP.Model.CSP.ServiceInfo> serviceInfoes = FindByIds(SearchIds, U_ServicePager.PageIndex, U_ServicePager.PageSize);
            BindServiceInfoListUI(serviceInfoes);
        }

        protected void Btn_Search_Click(object sender, EventArgs e)
        {


            if (Txt_Title.Value.Trim() == "")
            {
                SearchIds = GetIdsByUser();
            }
            else
            {
                SearchIds = FindIdsByTitle();
            }
            InitParm();
            ICollection<CSP.Model.CSP.ServiceInfo> serviceInfoes = FindByIds(SearchIds, U_ServicePager.PageIndex, U_ServicePager.PageSize);

            BindServiceInfoListUI(serviceInfoes);
        }

        protected void S_Status_SelectedIndexChanged(object sender, EventArgs e)
        {
            InitParm();
            List<int> ids = new List<int>();
            if (S_Status.SelectedValue != "")
            {
                ids = FindIdsByIdsAndStatus(SearchIds, (ServiceInfoStatus)Convert.ToInt32(S_Status.SelectedValue));
            }
            else
            {
                ids = SearchIds;
            }

            ICollection<CSP.Model.CSP.ServiceInfo> serviceInfoes = FindByIds(ids, U_ServicePager.PageIndex, U_ServicePager.PageSize);

            BindServiceInfoListUI(serviceInfoes);
        }

        /// <summary>
        /// 根据服务信息状态，获取服务信息Id
        /// </summary>
        /// <param name="status"></param>
        /// <returns></returns>
        protected string GetServiceInfoStatus(string status)
        {
            string result = "未上线";
            if ((ServiceInfoStatus)Convert.ToInt32(status) == ServiceInfoStatus.NotOnLine)
            {
                result = "未上线";
            }
            else if ((ServiceInfoStatus)Convert.ToInt32(status) == ServiceInfoStatus.OffLine)
            {
                result = "已下线";
            }
            else if ((ServiceInfoStatus)Convert.ToInt32(status) == ServiceInfoStatus.OnLine)
            {
                result = "已上线";
            }
            else if ((ServiceInfoStatus)Convert.ToInt32(status) == ServiceInfoStatus.Snapshot)
            {
                result = "快照";
            }
            return result;
        }

        /// <summary>
        /// 获取操作名称
        /// </summary>
        /// <param name="status"></param>
        /// <returns></returns>
        protected string GetOperateName(string status)
        {
            string result = "上线";
            //如果当前是未上线和上线状态那么,操作按钮名称为上线
            if ((ServiceInfoStatus)Convert.ToInt32(status) == ServiceInfoStatus.NotOnLine || (ServiceInfoStatus)Convert.ToInt32(status) == ServiceInfoStatus.OffLine)
            {
                result = "上线";
            }
            else if ((ServiceInfoStatus)Convert.ToInt32(status) == ServiceInfoStatus.OnLine)//如果当前是未上线和上线状态那么,操作按钮名称为上线
            {
                result = "下线";
            }

            return result;
        }

        protected string GetLastSecond(string date)
        {
            if (date == "")
            {
                return "0";
            }
            DateTime dt = Convert.ToDateTime(date);
            dt = dt.AddDays(7);
            return (dt - DateTime.Now).TotalSeconds.ToString();
        }

        /// <summary>
        /// 根据ServiceType 的Id获取结构
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        protected string GetServiceTypeName(string id)
        {
            string result = "";
            List<int> ids = new List<int>();
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();

            CSP.Model.CSP.ServiceType serviceType = null;
            using (IServiceTypeBll serviceTypeBll = bllFactory.GetServiceTypeBll())
            {
                for (int i = 0; i >= 0; i++)
                {
                    serviceType = serviceTypeBll.GetDataById(Convert.ToInt32(id));
                    id = serviceType.ParentId.ToString();

                    if (ids.Contains(serviceType.Id))
                    {
                        LoggerProvider.Error("ServiceInfo/ServiceType.aspx 出现死循环");
                        break;
                    }
                    ids.Add(serviceType.Id);

                    if (i == 0)
                    {
                        result = serviceType.Name;
                    }
                    else
                    {
                        result = serviceType.Name + "->" + result;
                    }

                    if (serviceType.ParentId == 0)
                    {
                        break;
                    }
                }
            }
            return result;

        }

        /// <summary>
        /// 删除服务信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private string RemoveServiceInfo(int id)
        {
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();

            CSP.Model.CSP.ServiceInfo serviceInfo = null;
            try
            {
                using (IServiceInfoBll serviceInfoBll = bllFactory.GetServiceInfoBll())
                {
                    serviceInfo = serviceInfoBll.DeleteByIdAndUser(id, UserProvider.UserName);
                    if (serviceInfo == null)
                    {
                        return "{\"status\":2,\"msg\":\"权限不足!\"}";
                    }
                    return "{\"status\":1,\"msg\":\"操作成功!\"}";
                }
            }
            catch (Exception ex)
            {
                LoggerProvider.Error(id, ex);
                return "{\"status\":0,\"msg\":\"操作失败!\"}";
            }

        }

        /// <summary>
        /// 更新服务状态
        /// </summary>
        /// <param name="id">服务Id</param>
        /// <param name="status">服务状态</param>
        /// <returns></returns>
        private string UpdateServiceStatus(int id, int status)
        {
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();

            CSP.Model.CSP.ServiceInfo serviceInfo = null;
            try
            {
                using (IServiceInfoBll serviceInfoBll = bllFactory.GetServiceInfoBll())
                {
                    serviceInfo = serviceInfoBll.UpdateStatus(id, (ServiceInfoStatus)status);
                    if (serviceInfo == null)
                    {
                        return "{\"status\":2,\"msg\":\"权限不足!\"}";
                    }
                    return "{\"status\":1,\"msg\":\"操作成功!\"}";
                }
            }
            catch (Exception ex)
            {
                LoggerProvider.Error(id, ex);
                return "{\"status\":0,\"msg\":\"操作失败!\"}";
            }
        }
    }
}